package com.pubinfo.passbook.common.service.master.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pubinfo.passbook.common.entity.TRuleCity;
import com.pubinfo.passbook.common.entity.TRuleDistrict;
import com.pubinfo.passbook.common.mapper.TRuleCityMapper;
import com.pubinfo.passbook.common.mapper.TRuleDistrictMapper;
import com.pubinfo.passbook.common.model.dto.rule.RuleDistrictParam;
import com.pubinfo.passbook.common.model.vo.base.JsonResult;
import com.pubinfo.passbook.common.model.vo.rule.DistrictIdRelevanceVo;
import com.pubinfo.passbook.common.service.master.TRuleDistrictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 *
 */
@Service
@Slf4j
public class TRuleDistrictServiceImpl extends ServiceImpl<TRuleDistrictMapper, TRuleDistrict>
    implements TRuleDistrictService {
  
  @Resource
  private TRuleCityMapper cityMapper;
  
  @Override
  public boolean saveRuleDistrict(TRuleDistrict ruleDistrict) {
    TRuleCity tRuleCity = cityMapper.selectById(ruleDistrict.getCityId());
    if (tRuleCity != null)
      return this.baseMapper.insert(ruleDistrict) > 0;
    return false;
  }
  
  @Override
  public JsonResult<String> removeRuleDistrict(String districtId) {
    List<DistrictIdRelevanceVo> districtIdRelevanceVos = this.baseMapper.selectDistrictIdRelevance(districtId);
    districtIdRelevanceVos.removeIf(Objects::isNull);
    if (!districtIdRelevanceVos.isEmpty())
      return JsonResult.error("该数据被其他表引用,删除失败");
    this.baseMapper.deleteDistrictDiseases(districtId);
    int result = this.baseMapper.deleteById(districtId);
    return result > 0 ? JsonResult.success("删除成功") : JsonResult.error("删除失败");
  }
  
  @Override
  public JsonResult<String> updateRuleDistrict(TRuleDistrict district) {
    TRuleCity tRuleCity = cityMapper.selectById(district.getCityId());
    if (tRuleCity == null)
      return JsonResult.error("没有相关的city数据,更新失败");
    this.baseMapper.updateById(district);
    return JsonResult.success("更新成功");
  }
  
  @Override
  public IPage<TRuleDistrict> selectRuleDistrict(RuleDistrictParam param) {
    IPage<TRuleDistrict> iPage = page(param.getPage("create_time"));
    return this.baseMapper.selectRuleDistrict(iPage, param);
  }
}




